import 'package:flutter/material.dart';
import 'package:sip_sdk_flutter/entitys/sip_sdk_constants.dart';

import '../../../utils/toast_utils.dart';
import '../ta/call_page.dart';
import '../ta/config_storage.dart';
import '../ta/sip_manage.dart';

// 全局SIP管理实例
SipCall? globalSipCall;

class SipCall {
  int? registrarStatusCode; // 注册状态码
  bool _isSdkInitialized = false; // SDK初始化状态
  bool _isRegistered = false; // 注册状态
  final String? deviceName; // 设备名称

  // SIP配置控制器
  final TextEditingController domainController =
  TextEditingController(text: "test.com");
  final TextEditingController usernameController =
  TextEditingController(text: "uniwin102");
  final TextEditingController passwordController =
  // TextEditingController(text: "uniwin123456");
  TextEditingController(text: "1234");
  final TextEditingController serverAddrController =
  // TextEditingController(text: "43.160.204.96");
  TextEditingController(text: "110.42.103.180");
  final TextEditingController serverPortController =
  TextEditingController(text: "5060");
  final TextEditingController proxyController =
  // TextEditingController(text: "43.160.204.96");
  TextEditingController(text: "110.42.103.180");
  final TextEditingController proxyPortController =
  TextEditingController(text: "5060");
  final TextEditingController callUsernameController =
  TextEditingController(text: "uniwin103");


  // STUN配置
  // bool stunEnable = false;
  bool stunEnable = true;
  bool stunEnableIPv6 = false;
  final TextEditingController stunServerController =
  TextEditingController(text: "120.79.7.237:3478");

  // TURN配置
  bool turnEnable = true;
  final TextEditingController turnServerController =
  TextEditingController(text: "120.79.7.237:3478");
  final TextEditingController turnRealmController =
  TextEditingController(text: "120.79.7.237");
  final TextEditingController turnUsernameController =
  TextEditingController(text: "test");
  final TextEditingController turnPasswordController =
  TextEditingController(text: "test");

  
  // SIP监听器
  SIPListener? sipListener;

  // 构造函数，接收deviceName参数
  SipCall({this.deviceName}) {
    _initListener();
  }

  // 初始化监听器
  void _initListener() {
    sipListener = SIPListener(
      // 处理注册状态回调
      onRegistrarState: (int state) {
        registrarStatusCode = state;
        _handleRegistrarStateChange();
      },
      // 处理初始化完成回调
      onInitCompleted: (int state, String message) {
        _handleInitCompleted(state, message);
      },
    );
    SIPManage().addListener(sipListener!);
  }

  // 初始化SIP配置和SDK
  Future<void> initialize() async {
    if (_isSdkInitialized || _isRegistered) return;

    await _loadConfigs();

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // 如果有传入deviceName，使用它替换username
      if (deviceName != null && deviceName!.isNotEmpty) {
        usernameController.text = deviceName!;
      }

      // 启动SDK初始化
      SIPManage.initialize();
    });
  }

  // 处理初始化完成回调
  void _handleInitCompleted(int state, String message) {
    if (state == 0) {
      // SDK初始化成功
      _isSdkInitialized = true;
      // Fluttertoast.showToast(msg: "SIP SDK初始化成功");

      // 初始化成功后执行注册
      _register();
    } else {
      // SDK初始化失败
      _isSdkInitialized = false;
      Toast.show("SIP SDK初始化失败: $message (状态码: $state)");
    }
  }

  // 处理注册状态变化
  void _handleRegistrarStateChange() {
    if (registrarStatusCode == 200) {
      // 注册成功
      _isRegistered = true;

      Toast.show("SIP注册成功");
      print("SIP注册成功");

      globalSipCall = this;
    } else if (registrarStatusCode != null) {
      // 注册失败
      _isRegistered = false;
      Toast.show("SIP注册失败，状态码: $registrarStatusCode");
    }
  }

  // 加载配置
  Future<void> _loadConfigs() async {
    // 加载SIP配置
    await ConfigStorage.load(ConfigStorage.sip_config).then((sipConfig) {
      Map<String, dynamic> config;
      if (sipConfig == null) {
        config = _getDefaultSipConfig();
        ConfigStorage.save(ConfigStorage.sip_config, config);
      } else {
        config = sipConfig;
      }
      _updateSipControllers(config);
    });

    // 加载STUN配置
    await ConfigStorage.load(ConfigStorage.stun_config).then((stunConfig) {
      Map<String, dynamic> config;
      if (stunConfig == null) {
        config = _getDefaultStunConfig();
        ConfigStorage.save(ConfigStorage.stun_config, config);
      } else {
        config = stunConfig;
      }
      _updateStunConfig(config);
    });

    // 加载TURN配置
    await ConfigStorage.load(ConfigStorage.turn_config).then((turnConfig) {
      Map<String, dynamic> config;
      if (turnConfig == null) {
        config = _getDefaultTurnConfig();
        ConfigStorage.save(ConfigStorage.turn_config, config);
      } else {
        config = turnConfig;
      }
      _updateTurnConfig(config);
    });
  }

  // 注册SIP
  Future<void> _register() async {
    // 只有当SDK初始化成功后才进行注册
    if (!_isSdkInitialized) {
      Toast.show("SDK未初始化，无法注册");
      return;
    }

    final config = {
      "domain": domainController.text,
      "username": usernameController.text,
      "password": passwordController.text,
      "serverAddr": serverAddrController.text,
      "serverPort": int.tryParse(serverPortController.text) ?? 5060,
      "proxy": proxyController.text,
      "proxyPort": int.tryParse(proxyPortController.text) ?? 5060,
      "callUsername": callUsernameController.text,
    };
    ConfigStorage.save(ConfigStorage.sip_config, config);
    SIPManage.registrar();
  }

  // 全局调用方法
  static void makeCall(BuildContext context, {String? username}) {
    // if (globalSipCall?._isRegistered != true) {
    //   Fluttertoast.showToast(msg: "SIP未注册成功，无法呼叫");
    //   return;
    // }

    Navigator.of(context).push(
      MaterialPageRoute(builder: (_) {
        int direction = 0; // 0.主动呼叫
        return CallPage(
          direction: direction,
          callType: SIPSDKConstants.SDK_CALL_TYPE_SERVER,
          username: username ?? globalSipCall?.callUsernameController.text ?? "",
          headers: const {
            "test": "test",
          },
        );
      }),
    );
  }

  // 默认配置获取方法
  Map<String, dynamic> _getDefaultSipConfig() {
    return {
      "domain": domainController.text,
      "username": usernameController.text,
      "password": passwordController.text,
      "serverAddr": serverAddrController.text,
      "serverPort": int.tryParse(serverPortController.text) ?? 5060,
      "proxy": proxyController.text,
      "proxyPort": int.tryParse(proxyPortController.text) ?? 5060,
      "callUsername": callUsernameController.text,
    };
  }

  Map<String, dynamic> _getDefaultStunConfig() {
    return {
      "enable": stunEnable,
      "enableIPv6": stunEnableIPv6,
      "server": stunServerController.text,
    };
  }

  Map<String, dynamic> _getDefaultTurnConfig() {
    return {
      "enable": turnEnable,
      "server": turnServerController.text,
      "realm": turnRealmController.text,
      "username": turnUsernameController.text,
      "password": turnPasswordController.text
    };
  }

  // 配置更新方法
  void _updateSipControllers(Map<String, dynamic> config) {
    domainController.text = config["domain"] ?? domainController.text;
    usernameController.text = config["username"] ?? usernameController.text;
    passwordController.text = config["password"] ?? passwordController.text;
    serverAddrController.text = config["serverAddr"] ?? serverAddrController.text;
    serverPortController.text = config["serverPort"]?.toString() ?? serverPortController.text;
    proxyController.text = config["proxy"] ?? proxyController.text;
    proxyPortController.text = config["proxyPort"]?.toString() ?? proxyPortController.text;
    callUsernameController.text = config["callUsername"]?.toString() ?? callUsernameController.text;
  }

  void _updateStunConfig(Map<String, dynamic> config) {
    stunEnable = config["enable"] ?? stunEnable;
    stunEnableIPv6 = config["enableIPv6"] ?? stunEnableIPv6;
    stunServerController.text = config["server"] ?? stunServerController.text;
  }

  void _updateTurnConfig(Map<String, dynamic> config) {
    turnEnable = config["enable"] ?? turnEnable;
    turnServerController.text = config["server"] ?? turnServerController.text;
    turnRealmController.text = config["realm"] ?? turnRealmController.text;
    turnUsernameController.text = config["username"] ?? turnUsernameController.text;
    turnPasswordController.text = config["password"] ?? turnPasswordController.text;
  }

  // 检查是否已注册成功
  bool get isRegistered => _isRegistered;

  // 检查SDK是否初始化成功
  bool get isSdkInitialized => _isSdkInitialized;
}

// 初始化方法，接收deviceName参数
void initializeSipInHomePage3(String deviceName) {
  // 如果还未初始化或初始化失败，使用新的deviceName重新初始化
  if (globalSipCall == null || !globalSipCall!.isSdkInitialized) {
    final sipCall = SipCall(deviceName: deviceName);
    sipCall.initialize();
  } else if (globalSipCall?.deviceName != deviceName) {
    // 如果deviceName改变，重新初始化
    globalSipCall = SipCall(deviceName: deviceName);
    globalSipCall?.initialize();
  }
}
